package com.geek.bulk;

import com.geek.ChainInvocationContext;
import com.geek.ReflectiveInvocationContext;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK-interceptor-enhancer 对JDK-interceptor扩展
 */
public class JDKInterceptorEnhancer {

    public static Object enchance(Object target, Object... interceptors) {
        ClassLoader classLoader = target.getClass().getClassLoader();
        return Proxy.newProxyInstance(classLoader,
                target.getClass().getInterfaces(),
                new InvocationHandlerAdapter(target, interceptors));
    }


        static class InvocationHandlerAdapter implements InvocationHandler {
            final Object target;
            final Object[] interceptors;

            InvocationHandlerAdapter(Object target, Object[] interceptors) {
                this.target = target;
                this.interceptors = interceptors;
            }

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                ReflectiveInvocationContext invocationContext = new ReflectiveInvocationContext(target, method, args);
                ChainInvocationContext chainInvocationContext = new ChainInvocationContext(invocationContext, interceptors);
                return chainInvocationContext.proceed();
            }
    }
}

